﻿// TODO: Move this file into the HtmlView folder
namespace Sedodream.Web.Common.View.HtmlView
{
using System;
using System.Web.Mvc;

public abstract class AbstractHtmlViewObject : IViewObject
{
    private bool mDisposed;

    public AbstractHtmlViewObject(IViewRequestContext requestContext, string name)
    {
        if (requestContext == null) 
        { throw new ArgumentNullException("requestContext"); }

        RequestContext = requestContext;
        Name = name;
    }

    public IViewRequestContext RequestContext
    {
        get;
        protected set;
    }

    #region IViewObject Members
    public object Attributes { get; set; }

    public string Name { get; set; }

    public abstract void StartView();

    public abstract void EndView();
    #endregion

    // based on System.Web.Mvc.HtmlHelper.GetModelStateValue
    public object GetModelStateValue(string key, Type destinationType)
    {
        object result = null;
        ModelState modelState;
        if (RequestContext.HtmlHelper.ViewData.ModelState.TryGetValue(
            key, out modelState))
        {
            result = modelState.Value.ConvertTo(destinationType, null);
        }

        return result;
    }

    #region IDisposable Members
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!mDisposed)
        {
            mDisposed = true;

            EndView();
        }
    }
    #endregion
}
}
